#coding:utf-8
import wsgiref.handlers
import os
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.api import users
import methods
import logging
def format_date(dt):
    return dt.strftime('%a, %d %b %Y %H:%M:%S GMT')

class PublicPage(webapp.RequestHandler):
    def render(self, template_file, template_value):
        path = os.path.join(os.path.dirname(__file__), template_file)

        # add user information to template_value
        template_value["user_greeting"] = methods.getUserGreeting(self.request.uri)
        
        self.response.out.write(template.render(path, template_value))
    
    def error(self,code):
        if code==400:
            self.response.set_status(code)
        else:
            self.response.set_status(code)
            
    def is_admin(self):
        return users.is_current_user_admin()
    
    def head(self, *args):
        return self.get(*args) 
    
class ListAllFiles(PublicPage):
    def get(self, page):
        index=0 if page=="" else int(page)
        files = methods.getAllFiles(index)
        prev,next = methods.getPageing(len(files), index)
        template_value={"files":files[:24],"prev":prev,"next":next}
        self.render('views/list.html', template_value)

class Error(PublicPage):
    def get(self):
        return self.error(404)

def main():
    application = webapp.WSGIApplication(
                                       [
                                        (r'/list/(?P<page>[0-9]*)', ListAllFiles)
                                       ], debug=True)
    wsgiref.handlers.CGIHandler().run(application)

if __name__ == "__main__":
    main()